package file;


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.Socket;


public class FileClientThread extends Thread {
	  private Socket socket;	 
	  private String home = "D:\\123\\Film\\";
	  private BufferedReader in_socket;
	  
	  public FileClientThread(Socket socket) {     

	    try {
		    this.socket = socket;
		    in_socket = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	  }
	  
	  public void run() {
		  String currentString = ""; 
	    try {
	      while (!socket.isClosed() && !currentString.equals("COMPLETETRANSFERT")) {	    	  
	    	  currentString = in_socket.readLine();
	    	  System.out.println("Fichier à envoyer : "+ currentString);
	    	  
	    	  File[] fichierDispo = DirectoryReader.listFiles(home);
	    	  
	    	  for (File file : fichierDispo) {
				System.out.println("Liste fichier dispo : "+file.getAbsolutePath());
	    	  }
	    	  
	    	  for (File file : fichierDispo) {
				if(file.getName().equals(currentString)){
					sendFile(file, this.socket);
					break;
				}
	    	  }
	    	        	
	      }
	      
	      socket.close();
	      System.out.println("Transfert finie !");
	    } catch (Exception e) {
	    }
	  }
	  
	  public static void sendFile(File file, Socket socketEnvoie) throws IOException, ClassNotFoundException {
		  	  
		    byte[] buf = new byte[1024];
		    OutputStream os = socketEnvoie.getOutputStream();
		    BufferedOutputStream out = new BufferedOutputStream(os, 1024);
		    FileInputStream in = new FileInputStream(file);
		    int i = 0;
		    int bytecount = 1024;
		    while ((i = in.read(buf, 0, 1024)) != -1) {
		      bytecount = bytecount + 1024;
		      out.write(buf, 0, i);
		      out.flush();
		    }
		    socketEnvoie.shutdownOutput(); /* important */
		    System.out.println("Bytes Sent :" + bytecount);

		    ObjectInputStream ois = new ObjectInputStream(socketEnvoie.getInputStream());
		    ois.skip(Long.MAX_VALUE);
		    String confirmation = (String) ois.readObject();
		    System.out.println("from server : " + confirmation);

		    out.close();
		    in.close();
		    
		  }

	  
}